package cn.ckx.coding.common.interceptor;

import cn.ckx.coding.common.annotation.login.Login;
import cn.ckx.coding.common.annotation.login.NotLogin;
import cn.ckx.coding.common.exception.CommonErrors;
import cn.ckx.coding.properties.AppProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 登录token校验
 *
 * @author kunxin.cai
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    private final AppProperties appProperties;
    
    public AuthorizationInterceptor(AppProperties appProperties){
        this.appProperties = appProperties;     
    }
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean validLogin = appProperties.getLogin().isEnabled();
        if(handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = ((HandlerMethod) handler);
            Login login = handlerMethod.getMethodAnnotation(Login.class);
            NotLogin notLogin = handlerMethod.getMethodAnnotation(NotLogin.class);

            if (login != null && notLogin != null) {
                throw CommonErrors.CODE_ERROR.msgFormat(request.getRequestURI(),
                        handlerMethod.getMethod().getName(), "Login和NotLogin不能同时使用！").build();
            }

            if (login != null) {
                validLogin = true;
            }
            if (notLogin != null) {
                validLogin = false;
            }
        }

        if (!validLogin) {
            return true;
        }

        //获取用户凭证
        String token = request.getHeader(appProperties.getLogin().getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(appProperties.getLogin().getHeader());
        }

        //凭证为空
        if(StringUtils.isBlank(token)){
            throw CommonErrors.PARAMETER_ERROR.msgFormat(appProperties.getLogin().getHeader()).build();
        }

        // TODO: 2023/4/12 *解析token,将userId塞到request请求中  ,    *userId替换admin
        request.setAttribute(appProperties.getLogin().getUserId(), "admin");

        return true;
    }
}
